home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / TAIL.C < prev    next >
C/C++ Source or Header  |  1993-10-02  |  26KB  |  1,018 lines

  1. /* tail -- output the last part of file(s)
  2.    Copyright (C) 1989, 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Can display any amount of data, unlike the Unix version, which uses
  19.    a fixed size buffer and therefore can only deliver a limited number
  20.    of lines.
  21.  
  22.    Options:
  23.    -b            Tail by N 512-byte blocks.
  24.    -c, --bytes=N[bkm]    Tail by N bytes
  25.             [or 512-byte blocks, kilobytes, or megabytes].
  26.    -f, --follow        Loop forever trying to read more characters at the
  27.             end of the file, on the assumption that the file
  28.             is growing.  Ignored if reading from a pipe.
  29.    -k            Tail by N kilobytes.
  30.    -N, -l, -n, --lines=N    Tail by N lines.
  31.    -m            Tail by N megabytes.
  32.    -q, --quiet, --silent    Never print filename headers.
  33.    -v, --verbose        Always print filename headers.
  34.  
  35.    If a number (N) starts with a `+', begin printing with the Nth item
  36.    from the start of each file, instead of from the end.
  37.  
  38.    Reads from standard input if no files are given or when a filename of
  39.    ``-'' is encountered.
  40.    By default, filename headers are printed only more than one file
  41.    is given.
  42.    By default, prints the last 10 lines (tail -n 10).
  43.  
  44.    Original version by Paul Rubin <phr@ocf.berkeley.edu>.
  45.    Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
  46.    tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.  */
  47.  
  48. #include <stdio.h>
  49. #include <io.h>
  50. #include <windows.h>
  51. #include "../lib/getopt.h"
  52. #include <sys/types.h>
  53. #include <signal.h>
  54. #include "system.h"
  55. #include "version.h"
  56.  
  57. /* Number of items to tail. */
  58. #define DEFAULT_NUMBER 10
  59.  
  60. /* Size of atomic reads. */
  61. #define BUFSIZE (512 * 8)
  62.  
  63. /* Number of bytes per item we are printing.
  64.    If 0, tail in lines. */
  65. static int unit_size;
  66.  
  67. /* If nonzero, read from the end of one file until killed. */
  68. static int forever;
  69.  
  70. /* If nonzero, read from the end of multiple files until killed.  */
  71. static int forever_multiple;
  72.  
  73. /* Array of file descriptors if forever_multiple is 1.  */
  74. static int *file_descs;
  75.  
  76. /* Array of file sizes if forever_multiple is 1.  */
  77. static off_t *file_sizes;
  78.  
  79. /* If nonzero, count from start of file instead of end. */
  80. static int from_start;
  81.  
  82. /* If nonzero, print filename headers. */
  83. static int print_headers;
  84.  
  85. /* When to print the filename banners. */
  86. enum header_mode
  87. {
  88.   multiple_files, always, never
  89. };
  90.  
  91. char *xmalloc ();
  92. void xwrite ();
  93. void error ();
  94.  
  95. static int file_lines ();
  96. static int pipe_bytes ();
  97. static int pipe_lines ();
  98. static int start_bytes ();
  99. static int start_lines ();
  100. static int tail ();
  101. static int tail_bytes ();
  102. static int tail_file ();
  103. static int tail_lines ();
  104. static long atou();
  105. static long dump_remainder ();
  106. static void tail_forever ();
  107. static void parse_unit ();
  108. static void usage ();
  109. static void write_header ();
  110.  
  111. /* The name this program was run with. */
  112. char *program_name;
  113.  
  114. /* Nonzero if we have ever read standard input. */
  115. static int have_read_stdin;
  116.  
  117. /* If non-zero, display usage information and exit.  */
  118. static int flag_help;
  119.  
  120. /* If non-zero, print the version on standard error.  */
  121. static int flag_version;
  122.  
  123. static struct option const long_options[] =
  124. {
  125.   {"bytes", required_argument, NULL, 'c'},
  126.   {"follow", no_argument, NULL, 'f'},
  127.   {"lines", required_argument, NULL, 'n'},
  128.   {"quiet", no_argument, NULL, 'q'},
  129.   {"silent", no_argument, NULL, 'q'},
  130.   {"verbose", no_argument, NULL, 'v'},
  131.   {"help", no_argument, &flag_help, 1},
  132.   {"version", no_argument, &flag_version, 1},
  133.   {NULL, 0, NULL, 0}
  134. };
  135.  
  136. void
  137. main (argc, argv)
  138.      int argc;
  139.      char **argv;
  140. {
  141.   enum header_mode header_mode = multiple_files;
  142.   int exit_status = 0;
  143.   /* If from_start, the number of items to skip before printing; otherwise,
  144.      the number of items at the end of the file to print.  Initially, -1
  145.      means the value has not been set. */
  146.   long number = -1;
  147.   int c;            /* Option character. */
  148.   int fileind;            /* Index in ARGV of first file name.  */
  149.  
  150.   program_name = argv[0];
  151.   have_read_stdin = 0;
  152.   unit_size = 0;
  153.   forever = forever_multiple = from_start = print_headers = 0;
  154.  
  155.   if (argc > 1
  156.       && ((argv[1][0] == '-' && ISDIGIT (argv[1][1]))
  157.       || (argv[1][0] == '+' && (ISDIGIT (argv[1][1]) || argv[1][1] == 0))))
  158.     {
  159.       /* Old option syntax: a dash or plus, one or more digits (zero digits
  160.      are acceptable with a plus), and one or more option letters. */
  161.       if (argv[1][0] == '+')
  162.     from_start = 1;
  163.       if (argv[1][1] != 0)
  164.     {
  165.       for (number = 0, ++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
  166.         number = number * 10 + *argv[1] - '0';
  167.       /* Parse any appended option letters. */
  168.       while (*argv[1])
  169.         {
  170.           switch (*argv[1])
  171.         {
  172.         case 'b':
  173.           unit_size = 512;
  174.           break;
  175.  
  176.         case 'c':
  177.           unit_size = 1;
  178.           break;
  179.  
  180.         case 'f':
  181.           forever = 1;
  182.           break;
  183.  
  184.         case 'k':
  185.           unit_size = 1024;
  186.           break;
  187.  
  188.         case 'l':
  189.           unit_size = 0;
  190.           break;
  191.  
  192.         case 'm':
  193.           unit_size = 1048576;
  194.           break;
  195.  
  196.         case 'q':
  197.           header_mode = never;
  198.           break;
  199.  
  200.         case 'v':
  201.           header_mode = always;
  202.           break;
  203.  
  204.         default:
  205.           error (0, 0, "unrecognized option `-%c'", *argv[1]);
  206.           usage ();
  207.         }
  208.           ++argv[1];
  209.         }
  210.     }
  211.       /* Make the options we just parsed invisible to getopt. */
  212.       argv[1] = argv[0];
  213.       argv++;
  214.       argc--;
  215.     }
  216.  
  217.   while ((c = getopt_long (argc, argv, "c:n:fqv", long_options, (int *) 0))
  218.      != EOF)
  219.     {
  220.       switch (c)
  221.     {
  222.     case 0:
  223.       break;
  224.  
  225.     case 'c':
  226.       unit_size = 1;
  227.       parse_unit (optarg);
  228.       goto getnum;
  229.     case 'n':
  230.       unit_size = 0;
  231.     getnum:
  232.       if (*optarg == '+')
  233.         {
  234.           from_start = 1;
  235.           ++optarg;
  236.         }
  237.       else if (*optarg == '-')
  238.         ++optarg;
  239.       number = atou (optarg);
  240.       if (number == -1)
  241.         error (1, 0, "invalid number `%s'", optarg);
  242.       break;
  243.  
  244.     case 'f':
  245.       forever = 1;
  246.       break;
  247.  
  248.     case 'q':
  249.       header_mode = never;
  250.       break;
  251.  
  252.     case 'v':
  253.       header_mode = always;
  254.       break;
  255.  
  256.     default:
  257.       usage ();
  258.     }
  259.     }
  260.  
  261.   if (flag_version)
  262.     {
  263.       fprintf (stderr, "%s\n", version_string);
  264.       exit (0);
  265.     }
  266.  
  267.   if (flag_help)
  268.     usage ();
  269.  
  270.   if (number == -1)
  271.     number = DEFAULT_NUMBER;
  272.  
  273.   /* To start printing with item `number' from the start of the file, skip
  274.      `number' - 1 items.  `tail +0' is actually meaningless, but for Unix
  275.      compatibility it's treated the same as `tail +1'. */
  276.   if (from_start)
  277.     {
  278.       if (number)
  279.     --number;
  280.     }
  281.  
  282.   if (unit_size > 1)
  283.     number *= unit_size;
  284.  
  285.   fileind = optind;
  286.  
  287.   if (optind < argc - 1 && forever)
  288.     {
  289.       forever_multiple = 1;
  290.       forever = 0;
  291.       file_descs = (int *) xmalloc ((argc - optind) * sizeof (int));
  292.       file_sizes = (off_t *) xmalloc ((argc - optind) * sizeof (off_t));
  293.     }
  294.  
  295.   if (header_mode == always
  296.       || (header_mode == multiple_files && optind < argc - 1))
  297.     print_headers = 1;
  298.  
  299.   if (optind == argc)
  300.     exit_status |= tail_file ("-", number, 0);
  301.  
  302.   for (; optind < argc; ++optind)
  303.     exit_status |= tail_file (argv[optind], number, optind - fileind);
  304.  
  305.   if (forever_multiple)
  306.     tail_forever (argv + fileind, argc - fileind);
  307.  
  308.   if (have_read_stdin && close (0) < 0)
  309.     error (1, errno, "-");
  310.   if (close (1) < 0)
  311.     error (1, errno, "write error");
  312.   exit (exit_status);
  313. }
  314.  
  315. /* Display the last NUMBER units of file FILENAME.
  316.    "-" for FILENAME means the standard input.
  317.    FILENUM is this file's index in the list of files the user gave.
  318.    Return 0 if successful, 1 if an error occurred. */
  319.  
  320. static int
  321. tail_file (filename, number, filenum)
  322.      char *filename;
  323.      long number;
  324.      int filenum;
  325. {
  326.   int fd, errors;
  327.   struct stat stats;
  328.  
  329.   if (!strcmp (filename, "-"))
  330.     {
  331.       have_read_stdin = 1;
  332.       filename = "standard input";
  333.       if (print_headers)
  334.     write_header (filename);
  335.       errors = tail (filename, 0, number);
  336.       if (forever_multiple)
  337.     {
  338.       if (fstat (0, &stats) < 0)
  339.         {
  340.           error (0, errno, "standard input");
  341.           errors = 1;
  342.         }
  343.       else if (!S_ISREG (stats.st_mode))
  344.         {
  345.           error (0, 0,
  346.              "standard input: cannot follow end of non-regular file");
  347.           errors = 1;
  348.         }
  349.       if (errors)
  350.         file_descs[filenum] = -1;
  351.       else
  352.         {
  353.           file_descs[filenum] = 0;
  354.           file_sizes[filenum] = stats.st_size;
  355.         }
  356.     }
  357.     }
  358.   else
  359.     {
  360.       /* Not standard input.  */
  361.       fd = open (filename, O_RDONLY);
  362.       if (fd == -1)
  363.     {
  364.       if (forever_multiple)
  365.         file_descs[filenum] = -1;
  366.       error (0, errno, "%s", filename);
  367.       errors = 1;
  368.     }
  369.       else
  370.     {
  371.       if (print_headers)
  372.         write_header (filename);
  373.       errors = tail (filename, fd, number);
  374.       if (forever_multiple)
  375.         {
  376.           if (fstat (fd, &stats) < 0)
  377.         {
  378.           error (0, errno, "%s", filename);
  379.           errors = 1;
  380.         }
  381.           else if (!S_ISREG (stats.st_mode))
  382.         {
  383.           error (0, 0, "%s: cannot follow end of non-regular file");
  384.           errors = 1;
  385.         }
  386.           if (errors)
  387.         {
  388.           close (fd);
  389.           file_descs[filenum] = -1;
  390.         }
  391.           else
  392.         {
  393.           file_descs[filenum] = fd;
  394.           file_sizes[filenum] = stats.st_size;
  395.         }
  396.         }
  397.       else
  398.         {
  399.           if (close (fd))
  400.         {
  401.           error (0, errno, "%s", filename);
  402.           errors = 1;
  403.         }
  404.         }
  405.     }
  406.     }
  407.  
  408.   return errors;
  409. }
  410.  
  411. static void
  412. write_header (filename)
  413.      char *filename;
  414. {
  415.   static int first_file = 1;
  416.  
  417.   if (first_file)
  418.     {
  419.       xwrite (1, "==> ", 4);
  420.       first_file = 0;
  421.     }
  422.   else
  423.     xwrite (1, "\n==> ", 5);
  424.   xwrite (1, filename, strlen (filename));
  425.   xwrite (1, " <==\n", 5);
  426. }
  427.  
  428. /* Display the last NUMBER units of file FILENAME, open for reading
  429.    in FD.
  430.    Return 0 if successful, 1 if an error occurred. */
  431.  
  432. static int
  433. tail (filename, fd, number)
  434.      char *filename;
  435.      int fd;
  436.      long number;
  437. {
  438.   if (unit_size)
  439.     return tail_bytes (filename, fd, number);
  440.   else
  441.     return tail_lines (filename, fd, number);
  442. }
  443.  
  444. /* Display the last part of file FILENAME, open for reading in FD,
  445.    using NUMBER characters.
  446.    Return 0 if successful, 1 if an error occurred. */
  447.  
  448. static int
  449. tail_bytes (filename, fd, number)
  450.      char *filename;
  451.      int fd;
  452.      long number;
  453. {
  454.   struct stat stats;
  455.  
  456.   /* Use fstat instead of checking for errno == ESPIPE because
  457.      lseek doesn't work on some special files but doesn't return an
  458.      error, either. */
  459.   if (fstat (fd, &stats))
  460.     {
  461.       error (0, errno, "%s", filename);
  462.       return 1;
  463.     }
  464.  
  465.   if (from_start)
  466.     {
  467.       if (S_ISREG (stats.st_mode))
  468.     lseek (fd, number, SEEK_SET);
  469.       else if (start_bytes (filename, fd, number))
  470.     return 1;
  471.       dump_remainder (filename, fd);
  472.     }
  473.   else
  474.     {
  475.       if (S_ISREG (stats.st_mode))
  476.     {
  477.       if (lseek (fd, 0L, SEEK_END) <= number)
  478.         /* The file is shorter than we want, or just the right size, so
  479.            print the whole file. */
  480.         lseek (fd, 0L, SEEK_SET);
  481.       else
  482.         /* The file is longer than we want, so go back. */
  483.         lseek (fd, -number, SEEK_END);
  484.       dump_remainder (filename, fd);
  485.     }
  486.       else
  487.     return pipe_bytes (filename, fd, number);
  488.     }
  489.   return 0;
  490. }
  491.  
  492. /* Display the last part of file FILENAME, open for reading on FD,
  493.    using NUMBER lines.
  494.    Return 0 if successful, 1 if an error occurred. */
  495.  
  496. static int
  497. tail_lines (filename, fd, number)
  498.      char *filename;
  499.      int fd;
  500.      long number;
  501. {
  502.   struct stat stats;
  503.   long length;
  504.  
  505.   if (fstat (fd, &stats))
  506.     {
  507.       error (0, errno, "%s", filename);
  508.       return 1;
  509.     }
  510.  
  511.   if (from_start)
  512.     {
  513.       if (start_lines (filename, fd, number))
  514.     return 1;
  515.       dump_remainder (filename, fd);
  516.     }
  517.   else
  518.     {
  519.       if (S_ISREG (stats.st_mode))
  520.     {
  521.       length = lseek (fd, 0L, SEEK_END);
  522.       if (length != 0 && file_lines (filename, fd, number, length))
  523.         return 1;
  524.       dump_remainder (filename, fd);
  525.     }
  526.       else
  527.     return pipe_lines (filename, fd, number);
  528.     }
  529.   return 0;
  530. }
  531.  
  532. /* Print the last NUMBER lines from the end of file FD.
  533.    Go backward through the file, reading `BUFSIZE' bytes at a time (except
  534.    probably the first), until we hit the start of the file or have
  535.    read NUMBER newlines.
  536.    POS starts out as the length of the file (the offset of the last
  537.    byte of the file + 1).
  538.    Return 0 if successful, 1 if an error occurred. */
  539.  
  540. static int
  541. file_lines (filename, fd, number, pos)
  542.      char *filename;
  543.      int fd;
  544.      long number;
  545.      long pos;
  546. {
  547.   char buffer[BUFSIZE];
  548.   int bytes_read;
  549.   int i;            /* Index into `buffer' for scanning. */
  550.  
  551.   if (number == 0)
  552.     return 0;
  553.  
  554.   /* Set `bytes_read' to the size of the last, probably partial, buffer;
  555.      0 < `bytes_read' <= `BUFSIZE'. */
  556.   bytes_read = pos % BUFSIZE;
  557.   if (bytes_read == 0)
  558.     bytes_read = BUFSIZE;
  559.   /* Make `pos' a multiple of `BUFSIZE' (0 if the file is short), so that all
  560.      reads will be on block boundaries, which might increase efficiency. */
  561.   pos -= bytes_read;
  562.   lseek (fd, pos, SEEK_SET);
  563.   bytes_read = read (fd, buffer, bytes_read);
  564.   if (bytes_read == -1)
  565.     {
  566.       error (0, errno, "%s", filename);
  567.       return 1;
  568.     }
  569.  
  570.   /* Count the incomplete line on files that don't end with a newline. */
  571.   if (bytes_read && buffer[bytes_read - 1] != '\n')
  572.     --number;
  573.  
  574.   do
  575.     {
  576.       /* Scan backward, counting the newlines in this bufferfull. */
  577.       for (i = bytes_read - 1; i >= 0; i--)
  578.     {
  579.       /* Have we counted the requested number of newlines yet? */
  580.       if (buffer[i] == '\n' && number-- == 0)
  581.         {
  582.           /* If this newline wasn't the last character in the buffer,
  583.              print the text after it. */
  584.           if (i != bytes_read - 1)
  585.         xwrite (1, &buffer[i + 1], bytes_read - (i + 1));
  586.           return 0;
  587.         }
  588.     }
  589.       /* Not enough newlines in that bufferfull. */
  590.       if (pos == 0)
  591.     {
  592.       /* Not enough lines in the file; print the entire file. */
  593.       lseek (fd, 0L, SEEK_SET);
  594.       return 0;
  595.     }
  596.       pos -= BUFSIZE;
  597.       lseek (fd, pos, SEEK_SET);
  598.     }
  599.   while ((bytes_read = read (fd, buffer, BUFSIZE)) > 0);
  600.   if (bytes_read == -1)
  601.     {
  602.       error (0, errno, "%s", filename);
  603.       return 1;
  604.     }
  605.   return 0;
  606. }
  607.  
  608. /* Print the last NUMBER lines from the end of the standard input,
  609.    open for reading as pipe FD.
  610.    Buffer the text as a linked list of LBUFFERs, adding them as needed.
  611.    Return 0 if successful, 1 if an error occured. */
  612.  
  613. static int
  614. pipe_lines (filename, fd, number)
  615.      char *filename;
  616.      int fd;
  617.      long number;
  618. {
  619.   struct linebuffer
  620.   {
  621.     int nbytes, nlines;
  622.     char buffer[BUFSIZE];
  623.     struct linebuffer *next;
  624.   };
  625.   typedef struct linebuffer LBUFFER;
  626.   LBUFFER *first, *last, *tmp;
  627.   int i;            /* Index into buffers. */
  628.   int total_lines = 0;        /* Total number of newlines in all buffers. */
  629.   int errors = 0;
  630.  
  631.   first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  632.   first->nbytes = first->nlines = 0;
  633.   first->next = NULL;
  634.   tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  635.  
  636.   /* Input is always read into a fresh buffer. */
  637.   while ((tmp->nbytes = read (fd, tmp->buffer, BUFSIZE)) > 0)
  638.     {
  639.       tmp->nlines = 0;
  640.       tmp->next = NULL;
  641.  
  642.       /* Count the number of newlines just read. */
  643.       for (i = 0; i < tmp->nbytes; i++)
  644.     if (tmp->buffer[i] == '\n')
  645.       ++tmp->nlines;
  646.       total_lines += tmp->nlines;
  647.  
  648.       /* If there is enough room in the last buffer read, just append the new
  649.          one to it.  This is because when reading from a pipe, `nbytes' can
  650.          often be very small. */
  651.       if (tmp->nbytes + last->nbytes < BUFSIZE)
  652.     {
  653.       bcopy (tmp->buffer, &last->buffer[last->nbytes], tmp->nbytes);
  654.       last->nbytes += tmp->nbytes;
  655.       last->nlines += tmp->nlines;
  656.     }
  657.       else
  658.     {
  659.       /* If there's not enough room, link the new buffer onto the end of
  660.          the list, then either free up the oldest buffer for the next
  661.          read if that would leave enough lines, or else malloc a new one.
  662.          Some compaction mechanism is possible but probably not
  663.          worthwhile. */
  664.       last = last->next = tmp;
  665.       if (total_lines - first->nlines > number)
  666.         {
  667.           tmp = first;
  668.           total_lines -= first->nlines;
  669.           first = first->next;
  670.         }
  671.       else
  672.         tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  673.     }
  674.     }
  675.   if (tmp->nbytes == -1)
  676.     {
  677.       error (0, errno, "%s", filename);
  678.       errors = 1;
  679.       free ((char *) tmp);
  680.       goto free_lbuffers;
  681.     }
  682.  
  683.   free ((char *) tmp);
  684.  
  685.   /* This prevents a core dump when the pipe contains no newlines. */
  686.   if (number == 0)
  687.     goto free_lbuffers;
  688.  
  689.   /* Count the incomplete line on files that don't end with a newline. */
  690.   if (last->buffer[last->nbytes - 1] != '\n')
  691.     {
  692.       ++last->nlines;
  693.       ++total_lines;
  694.     }
  695.  
  696.   /* Run through the list, printing lines.  First, skip over unneeded
  697.      buffers. */
  698.   for (tmp = first; total_lines - tmp->nlines > number; tmp = tmp->next)
  699.     total_lines -= tmp->nlines;
  700.  
  701.   /* Find the correct beginning, then print the rest of the file. */
  702.   if (total_lines > number)
  703.     {
  704.       char *cp;
  705.  
  706.       /* Skip `total_lines' - `number' newlines.  We made sure that
  707.          `total_lines' - `number' <= `tmp->nlines'. */
  708.       cp = tmp->buffer;
  709.       for (i = total_lines - number; i; --i)
  710.     while (*cp++ != '\n')
  711.       /* Do nothing. */ ;
  712.       i = cp - tmp->buffer;
  713.     }
  714.   else
  715.     i = 0;
  716.   xwrite (1, &tmp->buffer[i], tmp->nbytes - i);
  717.  
  718.   for (tmp = tmp->next; tmp; tmp = tmp->next)
  719.     xwrite (1, tmp->buffer, tmp->nbytes);
  720.  
  721. free_lbuffers:
  722.   while (first)
  723.     {
  724.       tmp = first->next;
  725.       free ((char *) first);
  726.       first = tmp;
  727.     }
  728.   return errors;
  729. }
  730.  
  731. /* Print the last NUMBER characters from the end of pipe FD.
  732.    This is a stripped down version of pipe_lines.
  733.    Return 0 if successful, 1 if an error occurred. */
  734.  
  735. static int
  736. pipe_bytes (filename, fd, number)
  737.      char *filename;
  738.      int fd;
  739.      long number;
  740. {
  741.   struct charbuffer
  742.   {
  743.     int nbytes;
  744.     char buffer[BUFSIZE];
  745.     struct charbuffer *next;
  746.   };
  747.   typedef struct charbuffer CBUFFER;
  748.   CBUFFER *first, *last, *tmp;
  749.   int i;            /* Index into buffers. */
  750.   int total_bytes = 0;        /* Total characters in all buffers. */
  751.   int errors = 0;
  752.  
  753.   first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  754.   first->nbytes = 0;
  755.   first->next = NULL;
  756.   tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  757.  
  758.   /* Input is always read into a fresh buffer. */
  759.   while ((tmp->nbytes = read (fd, tmp->buffer, BUFSIZE)) > 0)
  760.     {
  761.       tmp->next = NULL;
  762.  
  763.       total_bytes += tmp->nbytes;
  764.       /* If there is enough room in the last buffer read, just append the new
  765.          one to it.  This is because when reading from a pipe, `nbytes' can
  766.          often be very small. */
  767.       if (tmp->nbytes + last->nbytes < BUFSIZE)
  768.     {
  769.       bcopy (tmp->buffer, &last->buffer[last->nbytes], tmp->nbytes);
  770.       last->nbytes += tmp->nbytes;
  771.     }
  772.       else
  773.     {
  774.       /* If there's not enough room, link the new buffer onto the end of
  775.          the list, then either free up the oldest buffer for the next
  776.          read if that would leave enough characters, or else malloc a new
  777.          one.  Some compaction mechanism is possible but probably not
  778.          worthwhile. */
  779.       last = last->next = tmp;
  780.       if (total_bytes - first->nbytes > number)
  781.         {
  782.           tmp = first;
  783.           total_bytes -= first->nbytes;
  784.           first = first->next;
  785.         }
  786.       else
  787.         {
  788.           tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  789.         }
  790.     }
  791.     }
  792.   if (tmp->nbytes == -1)
  793.     {
  794.       error (0, errno, "%s", filename);
  795.       errors = 1;
  796.       free ((char *) tmp);
  797.       goto free_cbuffers;
  798.     }
  799.  
  800.   free ((char *) tmp);
  801.  
  802.   /* Run through the list, printing characters.  First, skip over unneeded
  803.      buffers. */
  804.   for (tmp = first; total_bytes - tmp->nbytes > number; tmp = tmp->next)
  805.     total_bytes -= tmp->nbytes;
  806.  
  807.   /* Find the correct beginning, then print the rest of the file.
  808.      We made sure that `total_bytes' - `number' <= `tmp->nbytes'. */
  809.   if (total_bytes > number)
  810.     i = total_bytes - number;
  811.   else
  812.     i = 0;
  813.   xwrite (1, &tmp->buffer[i], tmp->nbytes - i);
  814.  
  815.   for (tmp = tmp->next; tmp; tmp = tmp->next)
  816.     xwrite (1, tmp->buffer, tmp->nbytes);
  817.  
  818. free_cbuffers:
  819.   while (first)
  820.     {
  821.       tmp = first->next;
  822.       free ((char *) first);
  823.       first = tmp;
  824.     }
  825.   return errors;
  826. }
  827.  
  828. /* Skip NUMBER characters from the start of pipe FD, and print
  829.    any extra characters that were read beyond that.
  830.    Return 1 on error, 0 if ok.  */
  831.  
  832. static int
  833. start_bytes (filename, fd, number)
  834.      char *filename;
  835.      int fd;
  836.      long number;
  837. {
  838.   char buffer[BUFSIZE];
  839.   int bytes_read = 0;
  840.  
  841.   while (number > 0 && (bytes_read = read (fd, buffer, BUFSIZE)) > 0)
  842.     number -= bytes_read;
  843.   if (bytes_read == -1)
  844.     {
  845.       error (0, errno, "%s", filename);
  846.       return 1;
  847.     }
  848.   else if (number < 0)
  849.     xwrite (1, &buffer[bytes_read + number], -number);
  850.   return 0;
  851. }
  852.  
  853. /* Skip NUMBER lines at the start of file or pipe FD, and print
  854.    any extra characters that were read beyond that.
  855.    Return 1 on error, 0 if ok.  */
  856.  
  857. static int
  858. start_lines (filename, fd, number)
  859.      char *filename;
  860.      int fd;
  861.      long number;
  862. {
  863.   char buffer[BUFSIZE];
  864.   int bytes_read = 0;
  865.   int bytes_to_skip = 0;
  866.  
  867.   while (number && (bytes_read = read (fd, buffer, BUFSIZE)) > 0)
  868.     {
  869.       bytes_to_skip = 0;
  870.       while (bytes_to_skip < bytes_read)
  871.     if (buffer[bytes_to_skip++] == '\n' && --number == 0)
  872.       break;
  873.     }
  874.   if (bytes_read == -1)
  875.     {
  876.       error (0, errno, "%s", filename);
  877.       return 1;
  878.     }
  879.   else if (bytes_to_skip < bytes_read)
  880.     xwrite (1, &buffer[bytes_to_skip], bytes_read - bytes_to_skip);
  881.   return 0;
  882. }
  883.  
  884. /* Display file FILENAME from the current position in FD to the end.
  885.    If `forever' is nonzero, keep reading from the end of the file
  886.    until killed.  Return the number of bytes read from the file.  */
  887.  
  888. static long
  889. dump_remainder (filename, fd)
  890.      char *filename;
  891.      int fd;
  892. {
  893.   char buffer[BUFSIZE];
  894.   int bytes_read;
  895.   long total;
  896.  
  897.   total = 0;
  898. output:
  899.   while ((bytes_read = read (fd, buffer, BUFSIZE)) > 0)
  900.     {
  901.       xwrite (1, buffer, bytes_read);
  902.       total += bytes_read;
  903.     }
  904.   if (bytes_read == -1)
  905.     error (1, errno, "%s", filename);
  906.   if (forever)
  907.     {
  908.       Sleep (1);
  909.       goto output;
  910.     }
  911.   return total;
  912. }
  913.  
  914. /* Tail NFILES (>1) files forever until killed.  The file names are in
  915.    NAMES.  The open file descriptors are in `file_descs', and the size
  916.    at which we stopped tailing them is in `file_sizes'.  We loop over
  917.    each of them, doing an fstat to see if they have changed size.  If
  918.    none of them have changed size in one iteration, we sleep for a
  919.    second and try again.  We do this until the user interrupts us.  */
  920.  
  921. static void
  922. tail_forever (names, nfiles)
  923.      char **names;
  924.      int nfiles;
  925. {
  926.   int last;
  927.  
  928.   last = -1;
  929.  
  930.   while (1)
  931.     {
  932.       int i;
  933.       int changed;
  934.  
  935.       changed = 0;
  936.       for (i = 0; i < nfiles; i++)
  937.     {
  938.       struct stat stats;
  939.  
  940.       if (file_descs[i] < 0)
  941.         continue;
  942.       if (fstat (file_descs[i], &stats) < 0)
  943.         {
  944.           error (0, errno, "%s", names[i]);
  945.           file_descs[i] = -1;
  946.           continue;
  947.         }
  948.       if (stats.st_size == file_sizes[i])
  949.         continue;
  950.  
  951.       /* This file has changed size.  Print out what we can, and
  952.          then keep looping.  */
  953.       if (i != last)
  954.         {
  955.           write_header (names[i]);
  956.           last = i;
  957.         }
  958.       changed = 1;
  959.       file_sizes[i] += dump_remainder (names[i], file_descs[i]);
  960.     }
  961.  
  962.       /* If none of the files changed size, sleep.  */
  963.       if (! changed)
  964.     Sleep (1);
  965.     }
  966. }
  967.  
  968. static void
  969. parse_unit (str)
  970.      char *str;
  971. {
  972.   int arglen = strlen (str);
  973.  
  974.   if (arglen == 0)
  975.     return;
  976.  
  977.   switch (str[arglen - 1])
  978.     {
  979.     case 'b':
  980.       unit_size = 512;
  981.       str[arglen - 1] = '\0';
  982.       break;
  983.     case 'k':
  984.       unit_size = 1024;
  985.       str[arglen - 1] = '\0';
  986.       break;
  987.     case 'm':
  988.       unit_size = 1048576;
  989.       str[arglen - 1] = '\0';
  990.       break;
  991.     }
  992. }
  993.  
  994. /* Convert STR, a string of ASCII digits, into an unsigned integer.
  995.    Return -1 if STR does not represent a valid unsigned integer. */
  996.  
  997. static long
  998. atou (str)
  999.      char *str;
  1000. {
  1001.   unsigned long value;
  1002.  
  1003.   for (value = 0; ISDIGIT (*str); ++str)
  1004.     value = value * 10 + *str - '0';
  1005.   return *str ? -1 : value;
  1006. }
  1007.  
  1008. static void
  1009. usage ()
  1010. {
  1011.   fprintf (stderr, "\
  1012. Usage: %s [-c [+]N[bkm]] [-n [+]N] [-fqv] [--bytes=[+]N[bkm]] [--lines=[+]N]\n\
  1013.        [--follow] [--quiet] [--silent] [--verbose] [--help] [--version]\n\
  1014.        [file...]\n\
  1015.        %s [{-,+}Nbcfklmqv] [file...]\n", program_name, program_name);
  1016.   exit (1);
  1017. }
  1018.